from django.contrib import auth
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.shortcuts import render, redirect


# 登录界面
def login_page(request):
    return render(request, 'login/login.html')


# 注册界面
def register_page(request):
    return render(request, 'login/register.html')


# 注册处理
def register_(request):
    rz = request.POST.get('rz')
    if rz != 'gxu-internet-center-9':
        return render(request, 'login/register.html',
                      {
                          'tishi': '认证失败'
                      }
                      )
    username = request.POST.get('username')
    password = request.POST.get('password')
    password2 = request.POST.get('password2')
    if password != password2:
        return render(request, 'login/register.html',
                      {
                          'tishi': '请确认两次输入密码相同'
                      }
                      )
    email = request.POST.get('email')
    count = User.objects.filter(username=username).count()
    if count != 0:
        return render(request, 'login/register.html',
                      {
                          'tishi': '用户已存在,请更换用户名'
                      }
                      )
    count = User.objects.filter(email=email).count()
    if count >= 2:
        return render(request, 'login/register.html',
                      {
                          'tishi': '邮箱已注册2个,每个邮箱注册不能超过3个'
                      }
                      )
    User.objects.create_user(username=username, password=password, email=email)
    user_ = authenticate(username=username, password=password)
    login(request, user_)
    return render(request, 'login/register.html',
                  {
                      'tishi': '注册成功'
                  }
                  )


# 登录处理
def login_(request):
    if request.session.get('is_login', None):  # 不允许重复登录
        return redirect('/index/')
    username = request.POST.get('username')
    password = request.POST.get('password')
    if username =="" or password == "":
        return render(request, 'login/login.html',
                      {
                          'tishi': '请输入完整信息'
                      }
                      )
    user_ = authenticate(username=username, password=password)
    if user_:
        login(request, user_)
        return render(request, 'login/login.html',
                      {
                          'tishi': '登录成功'
                      }
                      )
    else:
        return render(request, 'login/login.html',
                      {
                          'tishi': '账号或密码错误'
                      }
                      )


# 注销操作
def logout_(request):
    auth.logout(request)
    return redirect('/')


# 注册或登录成功重定向到首页
def index_redirect(request):
    return redirect("/")
